using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ACM.cmsarea08;
using ACM.cmsarea08.Controls;
using ACM.cmsarea08.Administration;
using ACM.cmsarea08.Administration.Controls;


namespace ACM.cmsarea08.Administration.Core {
	public partial class GesMenu :  BaseDGridPage {
		private const int offSet = 20;
		protected Itan_DataGrid insVoci;
		private ACM.cmsarea08.Administration.Core.DBClass dclass = new cmsarea08.Administration.Core.DBClass();
		protected System.Web.UI.WebControls.DropDownList dropmenu; 
		protected System.Web.UI.WebControls.Button ref_btn;
		const string DBActionTable = "componenti";
		
		//private string _ids;
		private int TotalePagine {
			get {
				if(ViewState["pagine"]==null)
					return -1;
				else
					return (int)ViewState["pagine"];
			}
			set {
				ViewState["pagine"]=value;
			}
		}
		private int PaginaCorrente {
			get {
				if(ViewState["PaginaCorrente"]==null)
					return -1;
				else
					return (int)ViewState["PaginaCorrente"];
			}
			set {
				ViewState["PaginaCorrente"]=value;
			}
		}
		private string _idm {
			get {
				if(ViewState["idm"]==null){
					if(Request.QueryString["idm"]!=null)
						return Request.QueryString["idm"].ToString();
					else
						return "-1";
				}
				else
					return ViewState["idm"].ToString();
			}
			set {
				ViewState["idm"]=value;
			}
		}
		
		
		
		override protected void OnInit(EventArgs e)
		{
			if(ACM.cmsarea08.Users.CurrentUser.Role.Score>400)
				Response.Redirect("/loginadm.aspx?returnurl="+
								HttpUtility.UrlEncode(Request.ServerVariables["SCRIPT_NAME"].ToString()+
				                   (Request.ServerVariables["QUERY_STRING"].ToString()==""?"":"?"+Request.ServerVariables["QUERY_STRING"].ToString()))
	);
			else if(ACM.cmsarea08.Users.CurrentUser.Role.Score>200)
				Response.Redirect("/administration/accessdeny.aspx");
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent()
		{
			if(this.Master is ACM.cmsarea08.Administration.Core.ListerPrivate) {
//				((itareanet.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.EditMode=TipiPagineLista.BlocchiVisivi;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowAddNewHref=false;		
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.AddNewIsPopup=false;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowClone=true;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowAddDefault=false;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowAddNew=false;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.DBActionTable="moduli";
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.HelpPath="/administration/docs/Menu.html";
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.DataSourceChanged+= new EventHandler(RicaricaDati);
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.DeletingQueryCheck="select(select count(*) from " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"menu_elemento where menu_contenitore='{0}') +" +
					"(select if(lockid=-1,0,1) from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "moduli where id='{0}');";
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.DeletingQueryCheckFailMessage="";
				CustomHref cmd_tmp = new CustomHref("ADD_NEW","<img src=\"/administration/template/img/spacer.gif\" alt=\"inserisci\" />inserisci","Insert New","smoothbox","/administration/controls/optmenu.aspx?keepThis=true&TB_iframe=true&width=600&height=450","") ;
				cmd_tmp.Class="jmsadd smoothbox";
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.setCustomHRefs(cmd_tmp);
			}
			
			this.Load += new System.EventHandler(this.Page_Load);
			insVoci.CambiaPagina += new Itan_DataGridEventHandler(CambiaPagina);
			ref_btn.Command += new CommandEventHandler(this.CambiaSezione);
			insVoci.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(GrigliaCommand);
			insVoci.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(MentreCaricaDati);
		}
	
		private void Page_Load(object o , EventArgs e) {
			
		//	dropmenu.SelectedValue = _idm;
			insVoci.Title = rm.GetString("menu_list");
			ref_btn.Text = rm.GetString("refresh");
			if(!Page.IsPostBack) {
				CaricaDati();
				
				
			}
		}
		private void CaricaDati() {
			if(PaginaCorrente==-1)
				PaginaCorrente = 0;
			if( _idm == string.Empty && Request.QueryString["idm"]!=null ) {
					_idm = Request.QueryString["idm"].ToString();
			}
			
			
			//rimepimento dropdown
			DataSet dsdrop = dclass.ExecuteDataset("select id,titolo from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "componenti " +
			                                       "where isMenu='1'");
			dropmenu.Items.Clear();
			dropmenu.Items.Add(new ListItem("--","-1"));
			if(dsdrop!=null){
				
				foreach(DataRow dr in dsdrop.Tables[0].Rows){
					dropmenu.Items.Add(new ListItem(dr["titolo"].ToString(),dr["id"].ToString()));
				}
				
			
				dropmenu.SelectedValue = _idm;
				dropmenu.DataBind();
			} 
			
			
			if(ElencoGriglia==null) {
				insVoci.DataSource=null;
//				if(_idm!=null && _idm.Trim()!="" && _idm!="-1"){
//					Response.Write(Request.QueryString["idm"].ToString() + "<hr>" + mio1.SelectedSection+"<hr>");
					
//					Response.Write(Request.QueryString["idm"].ToString() + "<hr>" + mio1.SelectedSection );
				try{
					string query = "select " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.id as id," +  
						ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.titolo as titolo," +
						ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.lockid as lockid," +
						ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.data_mod as data_mod," +  
						ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.enabled as enabled,"+
						ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"componenti.titolo as nome_componente," +
						ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"blocco_visivo.titolo as bloccov," +
						"(select username from "+dclass.TablePrefix+"utenti where id = "+dclass.TablePrefix + "moduli.lockid) as lockedby, " +
					    "(select count(*) from " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"menu_elemento where menu_contenitore=" +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.id) as figli " +
					                                   "FROM " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli " +
					                                   "join " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"componenti on " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.id_componente = " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"componenti.id " +
					                                   "left join " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"blocco_visivo on " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"moduli.blocco_visivo = " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"blocco_visivo.id " +
					                                   "where " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +"componenti.isMenu='1';";
					
					//Response.Write("query:<br>" + query + "<hr>");
					DataSet ds = dclass.ExecuteDataset(query);
//					DataSet ds = dclass.ExecuteDataset("select *,(select count(*) from " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + 
//					                                   "componenti where isMenu='1') as uconteggio from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "componenti " +
//		                           					   "where isMenu='1' ;");
    				
					ElencoGriglia = ds;
					//return;
				}
				catch(Exception ec){
					Response.Write(ec.ToString());
				}
					
//				}
//				else{
//					Response.Write("errore");
////					DataSet ds = dclass.ExecuteDataset("select *,(select count(*) from " +  ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle +
////					                                   "componenti where isMenu='1') as uconteggio from " + ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle + "componenti " +
////		                           					   "where isMenu='1' ;");
////    				
////					ElencoGriglia = ds;
////					return;
//				}
				
			}
			if(ElencoGriglia==null) {
				insVoci.Visible=false;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowClone=false;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowDelete=false;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ListButtonBind();
				return;
			}
			if(ElencoGriglia.Tables[0].Columns.Contains("uconteggio") && 
			   ElencoGriglia.Tables[0].Rows.Count>0 ) {
				int totaleC =0;
				Int32.TryParse(ElencoGriglia.Tables[0].Rows[0]["uconteggio"].ToString(), out totaleC);
				TotalePagine = (totaleC/offSet) + (totaleC%offSet>1?1:0);
				
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowClone=
					ACM.cmsarea08.Users.CurrentUser.Role.Layout.CanManageMenu && true;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ShowDelete=
					ACM.cmsarea08.Users.CurrentUser.Role.Layout.CanManageMenu && true;
				((ACM.cmsarea08.Administration.Core.ListerPrivate)this.Master).adm_button.ListButtonBind();
			}


			insVoci.PageNum=TotalePagine;
			insVoci.CurrentPage = PaginaCorrente;
			insVoci.Visible=true;
			if(insVoci.DataSource==null) {
				insVoci.DataSource = ElencoGriglia;
				insVoci.DataBind();
			}
		}
//		private void Inserisci_Menu(object o, EventArgs e){
//			
//			Response.Redirect("edit_menu.aspx?new=1&idf=0");
//			
//		}
		
		private void CambiaPagina(object o, Itan_DataGridEventArgs e) {
			PaginaCorrente=e.NewPage;
			ElencoGriglia=null;
			CaricaDati();
		}

		private void CambiaSezione(object o, CommandEventArgs e) {
			_idm = dropmenu.SelectedValue;			
			ElencoGriglia=null;
			CaricaDati();
		}
		
		private void RicaricaDati(object o, EventArgs e) {
			ElencoGriglia=null;
			CaricaDati();
		}
		
		private void MentreCaricaDati(object o, DataGridItemEventArgs e) {
			//enable_me
			if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
				LinkButton lkb;
				lkb = (LinkButton)e.Item.FindControl("enable_me");
				if(lkb!=null) {
					string ena = ((DataRowView)e.Item.DataItem)["enabled"].ToString();
					lkb.CommandName="Abilita";
					lkb.CommandArgument=((DataRowView)e.Item.DataItem)["id"].ToString();
					lkb.Text = 
						(ena=="1"? ("<img border=\"0\" class=\"jmsenabled1_sm\" src=\"../template/img/spacer.gif\" alt=\""+ rm.GetString("enabled") +"\" />"):
						 ("<img border=\"0\" class=\"jmsenabled0_sm\" src=\"../template/img/spacer.gif\" alt=\""+ rm.GetString("disabled") +"\" />"))
						;
				}
			}
			
		}
		private void GrigliaCommand(object o, DataGridCommandEventArgs e) {
			//enable_me
			string id="";
			if(e.CommandName.ToString() == "Abilita") {
				id=e.CommandArgument.ToString();
				int reso = dclass.ExecuteScalar("update "+ACM.cmsarea08.mainconfiguration.MainConf.PrefissoTabelle+"moduli " +
				"set " +
				" enabled = if(enabled='1','0','1') " +				
				"where id = " +id +" limit 1;");
				if(reso>0) {
					ElencoGriglia=null;
					CaricaDati();
				} else {
					
				}
			}
		}
		
	}
	
}
